﻿#region MIT license
/*
 Copyright (c) 2009-2010 Joxon Productions <joxonproductions@gmail.com>

 Permission is hereby granted, free of charge, to any person
 obtaining a copy of this software and associated documentation
 files (the "Software"), to deal in the Software without
 restriction, including without limitation the rights to use,
 copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the
 Software is furnished to do so, subject to the following
 conditions:

 The above copyright notice and this permission notice shall be
 included in all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 OTHER DEALINGS IN THE SOFTWARE.
*/
#endregion

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

namespace JAsyncServerLib
{
    public class JClient
    {        
        public Object Tag = null; // Tag can be set to anything :)
        private byte[] m_readBuffer = new byte[0];
        private byte[] m_writeBuffer = new byte[0];
        private Socket m_Socket;
        private Socket m_listenSocket;
        private Boolean m_sendingData = false;
        private double m_lastActivity = 0;
        private Boolean m_Pending = false;
        public string objectGuid = System.Guid.NewGuid().ToString();
        public string SendLock = System.Guid.NewGuid().ToString();

        public JClient(Socket socket, JServer server)
        {
            m_Socket = socket;
            Server = server;
            m_lastActivity = UnixTime.GetSeconds();
        }

        public JClient()
        {

        }

        public JServer Server 
        {
            get;
            internal set;
        }

        public JClientMgr Manager()
        {
            return Server.ClientManager;
        }

        public Socket RawRocket
        {
            get
            {
                return m_Socket;
            }
        }

        public void Disconnect(bool ignored)
        {
            if (m_Socket == null || !m_Socket.Connected) { return; }

            OnDisconnect();
            m_Socket.Disconnect(false);

        }

        public void Disconnect()
        {
            if (m_Socket == null || !m_Socket.Connected) { return; }

            OnDisconnect();
            m_Socket.Disconnect(false);
        }

        public void Shutdown(SocketShutdown shutType)
        {
            if (m_Socket == null || !m_Socket.Connected) { return; }

            OnDisconnect();

            m_Socket.Shutdown(shutType);
            m_Socket.Close();
        }

        public void Send(byte[] bytes)
        {
            lock (SendLock)
            {
                int oldSize = m_writeBuffer.Length;
                if (m_writeBuffer.Length == 0)
                {
                    m_writeBuffer = bytes;
                }
                else
                {
                    JByte.Resize(ref m_writeBuffer, m_writeBuffer.Length + bytes.Length);
                    Array.Copy(bytes, 0, m_writeBuffer, oldSize, bytes.Length);
                }
            }
        }

        public byte[] GetPendingBytes()
        {
            return m_writeBuffer;
        }

        public int GetPendingBytesCount() // Use to decide when to kick ppl when to much data is pending
        {
            return m_writeBuffer.Length;
        }

        public void SendBuffer()
        {
            lock (SendLock)
            {
                // To prevent more than 1 thread... (if m_sendingData is true, new incoming data will be handled automaticly)
                if (m_sendingData)
                    return;

                if (m_writeBuffer.Length > 0)
                {
                    // Begin sending the data to the remote device.
                    JClientObject theSocPkt = new JClientObject();
                    theSocPkt.CurrentSocket = m_Socket;
                    theSocPkt.Client = this;
                    theSocPkt.ListenSocket = m_listenSocket;
                    theSocPkt.Server = Server;

                    m_sendingData = true;
                    OnWrite();
                    m_Socket.BeginSend(m_writeBuffer, 0, m_writeBuffer.Length, 0,
                                new AsyncCallback(SocketOnWrite), theSocPkt);
                }
            }
        }

        public void socketOnAccept(JServer server)
        {
            m_listenSocket = server.RawSocket;

            Server = server;
        }

        public string GetRemoteIP()
        {
            return ((IPEndPoint)m_Socket.RemoteEndPoint).Address.ToString();
        }

        public int GetRemotePort()
        {
            return ((IPEndPoint)m_Socket.RemoteEndPoint).Port;
        }

        public Boolean IsPending()
        {
            return m_Pending;
        }

        /// <summary>
        /// Triggered when data is read from the stream
        /// </summary>
        /// <param name="bytesRead">Amount of bytes read</param>
        protected virtual void OnRead(int bytesRead)
        {

        }
        /// <summary>
        /// Triggered when data is about to be written
        /// </summary>
        protected virtual void OnWrite()
        {

        }

        /// <summary>
        /// Triggered once a disconnect occurs
        /// </summary>
        protected virtual void OnDisconnect()
        {

        }

        public void SocketOnRead(IAsyncResult asyn)
        {
            try
            {
                var socketData = (JClientObject)asyn.AsyncState;

                int iRx = m_Socket.EndReceive(asyn);

                // When eventOnRead gets called with no data: disconnect
                if (iRx == 0)
                {
                    OnDisconnect();
                    Server.CallOnDisconnect(this);
                    return;
                }

                int oldSize = 0;
                oldSize = m_readBuffer.Length;
                JByte.Resize(ref m_readBuffer, iRx);
                Array.Copy(socketData.DataBuffer, 0, m_readBuffer, 0, iRx);

                OnRead(iRx);
                Server.CallOnReceive(this, m_readBuffer);

                m_readBuffer = new  byte[0];
                Thread.Sleep(0);

                Server.ListenForData(this); // Start listening again for data :) // TODO Move to JClient
            }
            catch (ObjectDisposedException exx)
            {
                System.Diagnostics.Debugger.Log(0, "1", "OnRead: Socket has been closed\n");
                Server.CallOnException(exx);
            }
            catch (SocketException se)
            {
                OnDisconnect();

                Server.CallOnError(se.ToString(), se);
                Server.CallOnDisconnect(this);
            }
            catch(Exception ex)
            {
                Server.CallOnException(ex);
            }
        }


        public void SocketOnWrite(IAsyncResult asyn)
        {
            try
            {
                var socketData = (JClientObject)asyn.AsyncState;

                int iTx = 0;
                iTx = socketData.CurrentSocket.EndSend(asyn);
                lock (SendLock)
                {
                    m_writeBuffer = JByte.Copy(ref m_writeBuffer, iTx);
                    m_sendingData = false;
                    if (m_writeBuffer.Length > 0)
                    {
                        SendBuffer(); // Still some bytes left to send, send it again
                    }
                }
            }
            catch (ObjectDisposedException exx)
            {
                System.Diagnostics.Debugger.Log(0, "1", "OnRead: Socket has been closed\n");
                Server.CallOnException(exx);
            }
            catch (Exception se)
            {
                Server.CallOnException(se);
            }
        }

        public Object GetTag()
        {
            return Tag;
        }

        public void SetTag(Object tag)
        {
            Tag = tag;
        }

        public Boolean Update(Double Dummy)
        {
            if ((RawRocket == null) || (m_Socket.Connected == false))
            {
                return false;
            }

            if (!m_sendingData)
            {
                SendBuffer();
            }

            return true;
        }

        public void Init(Socket socket, JServer server)
        {
            m_Socket = socket;
            Server = server;
            m_lastActivity = UnixTime.GetSeconds();
        }
    }
}
